package com.shooter.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {

    //是否正确的手机号码
    public static boolean isPhone(String mp) {
        Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(17[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mp);
        return m.matches();
    }

    //获取 随机数 length=长度
    public static String getRand(int length) {
        String rand = "";
        for (int i = 0; i < length; i++) {
            rand += "" + (int) (Math.random() * 10);
        }
        return rand;
    }

    //获取流中字符串
    public static String toInputString(InputStream input) {
        String s = "";
        try {
            byte[] b = new byte[input.available()];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = len = input.read(b);
            baos.write(b, 0, len);
            baos.flush();
            s = new String(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 检查不为空
     *
     * @param str
     * @return true表示有参数 false没有参数
     */
    public static boolean checkStringNoNull(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
        return true;
    }

    /**
     * 方法用途: 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序），并且生成url参数串<br>
     * 实现步骤: <br>
     *
     * @param paraMap    要排序的Map对象
     * @param urlEncode  是否需要URLENCODE
     * @param keyToLower 是否需要将Key转换为全小写
     *                   true:key转化成小写，false:不转化
     * @return
     */
    public static String formatUrlMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower) {
        String buff = "";
        Map<String, String> tmpMap = paraMap;
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<>(tmpMap.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造URL 键值对的格式
            StringBuilder buf = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (checkStringNoNull(item.getValue())) {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (urlEncode) {
                        val = URLEncoder.encode(val, "utf-8");
                    }
                    if (keyToLower) {
                        buf.append(key + "=" + val);
                    } else {
                        buf.append(key + "=" + val);
                    }
                    buf.append("&");
                }

            }
            buff = buf.toString();
            if (buff.isEmpty() == false) {
                buff = buff.substring(0, buff.length() - 1);
            }
        } catch (Exception e) {
            return null;
        }
        return buff;
    }
}
